package oa.hleast.xswl.controller.app;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.result.Result;
import oa.hleast.common.utils.JsonUtil;
import oa.hleast.xswl.common.config.ServerProps;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 302
 * @description
 * @date 2021/3/17
 */
@Api(tags = "【移动端】浙里办映射")
@RestController
@RequestMapping("/api.app/v1/zlb")
@AllArgsConstructor
@Slf4j
public class MappingController {

    private final ServerProps serverProps;

    @PostMapping("/grape")
    public Result postMapping(HttpServletRequest request, HttpServletResponse response) {
        return mapping(request, response);
    }

    private Result mapping(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> param = new HashMap<>();
        try {
            String body = readAsChars(request);
            log.info("body = {}", body);
            Map<String, Object> tempParam = JsonUtil.string2Collection(body, new TypeReference<Map<String, Object>>() {
            });
            Object bodyParam = tempParam.get("bodyParam");
            log.info("bodyParam = {}", bodyParam);
            param = JsonUtil.string2Collection(JsonUtil.obj2String(bodyParam), new TypeReference<Map<String, Object>>() {
            });
            log.info("param  = {}", param);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String authorization = request.getHeader("token");
        String methodPath = request.getHeader("address");
        String method = request.getHeader("type");
        String contentType = request.getHeader("content");
        log.info("methodPath = {},method = {},contentType = {},authorization = {}", methodPath, method, contentType, authorization);

        String url = "http://127.0.0.1:"+ serverProps.getPort() + methodPath;
        Map<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", request.getHeader("content"));
        headerParams.put("Authorization", authorization);


        log.info("headerParams = {}", headerParams);
        // get 请求
        if ("0".equals(method)) {
            url = HttpUtil.urlWithForm(url, param, StandardCharsets.UTF_8, true);
            log.info("url = {}", url);
            String result = HttpRequest.get(url)
                    .headerMap(headerParams, true)
                    .timeout(20000)
                    .execute().body();
            log.info("get result = {}", result);
            return JsonUtil.string2Obj(result, Result.class);
        } else if ("1".equals(method) && ContentType.JSON.getValue().equals(contentType)) {
            // post 请求
            String result = HttpRequest.post(url)
                    .headerMap(headerParams, true)
                    .body(JsonUtil.obj2String(param))
                    .timeout(20000)
                    .execute().body();
            log.info("post json result = {}", result);
            return JsonUtil.string2Obj(result, Result.class);
        } else if ("1".equals(method) && ContentType.FORM_URLENCODED.getValue().equals(contentType)) {
            // post 请求
            String result = HttpRequest.post(url)
                    .headerMap(headerParams, true)
                    .form(param)
                    .timeout(20000)
                    .execute().body();
            log.info("post form result = {}", result);
            return JsonUtil.string2Obj(result, Result.class);
        }

        log.info("没有对应的请求类型 method  = {}", method);
        return null;
    }

    /** 字符串读取 */
    public String readAsChars(HttpServletRequest request) {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}
